﻿using SmartTracking.Infrastructure.Interfaces;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SmartTracking.Infrastructure.Implements
{
    public class BaseRepository<T> : IBaseRepository<T> where T: class
    {
        private readonly DataDbContext dbContext;

        public BaseRepository(DataDbContext dbContext)
        {
            this.dbContext = dbContext;
        }

        public DataDbContext DB { get { return dbContext; } }

        public async Task<int> AddAsync(T entity)
        {
            await dbContext.Set<T>().AddAsync(entity);
            return await dbContext.SaveChangesAsync();
        }

        public async Task<int> AddRangeAsync(List<T> list)
        {
            await dbContext.Set<T>().AddRangeAsync(list);
            return await dbContext.SaveChangesAsync();
        }

        public Task<int> DeleteAsync(T entity)
        {
            dbContext.Set<T>().Remove(entity);
            return dbContext.SaveChangesAsync();
        }

        public Task<int> DeleteRangeAsync(List<T> list)
        {
            dbContext.Set<T>().RemoveRange(list);
            return dbContext.SaveChangesAsync();
        }

        public IQueryable<T> GetAll()
        {
            return dbContext.Set<T>().AsQueryable();
        }

        public Task<int> UpdateAsync(T entity)
        {
            dbContext.Set<T>().Update(entity);
            return dbContext.SaveChangesAsync();
        }

        public Task<int> UpdateRangeAsync(List<T> list)
        {
            foreach (var entity in list)
            {
                var entry = dbContext.Entry(entity);
                if (entry.State == EntityState.Detached)
                {
                    dbContext.Set<T>().Attach(entity);
                }
                entry.State = EntityState.Modified;
            }
            return dbContext.SaveChangesAsync();
        }

        /// <summary>
        /// 根据Id异步获取数据
        /// </summary>
        /// <param name="Id"> </param>
        /// <returns></returns>
        public async Task<T> GetByIdAsync(int Id)
        {
            return await dbContext.Set<T>().FindAsync(Id);
        }
    }
}
